package com.pediOnline.Controlador;

import java.security.Principal;


import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.GenericJDBCException;
import org.hibernate.exception.JDBCConnectionException;

import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.pediOnline.entities.User;
import com.pediOnline.persistense.UserDAO;

@RequestMapping("/auth")
@Controller
public class LoginLogoutController {

 private UserDAO userDAO;
 public SecurityContextHolder securityContextHolder = new SecurityContextHolder();
 
 public UserDAO getUserDAO() {
	return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
	this.userDAO = userDAO;
}

protected static Logger logger = Logger.getLogger("controller");

	@Autowired
	public LoginLogoutController(UserDAO userDAO){
		this.userDAO = userDAO;
	}
 
@RequestMapping(value = "/login", method = RequestMethod.GET)
 public String getLoginPage(@RequestParam(value="error", required=false) boolean error, 
   ModelMap model, Principal principal) {
	
	if (error == true) {
   // Assign an error message
   model.put("error", "You have entered an invalid username or password!");
  } else {
   model.put("error", "");
  }
	System.out.println(principal);
	
  // This will resolve to /WEB-INF/jsp/loginpage.jsp
  return "loginpage";
 }
  
 @RequestMapping(value = "/denied", method = RequestMethod.GET)
  public String getDeniedPage() {
  return "deniedpage";
 }
 
 @RequestMapping(value = "/create", method = RequestMethod.POST)
 public String createUser(HttpServletRequest request, ModelMap model) throws Throwable{
	 String page = "";
	 String username = request.getParameter("newUsername");
	 String password = request.getParameter("newPassword");
	 User newUser = new User(username, password);
	
	try {
		 getUserDAO().save(newUser);
		 UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
		 SecurityContextHolder.getContext().setAuthentication(authRequest);
	} catch (PersistenceException pe) {
		page = "loginpage";
		try{
		throw pe.getCause();}
		
		//Catch cause of Persistance Exception
		catch (JDBCConnectionException e) {
			page = "dbDown";
		}
		catch (ConstraintViolationException e) {
			model.put("singUpError","Username is not available");
		}
	}
	 
	 if (page == ""){page = "redirect:/TODO/main/inicio";}
	 
	 return page;
 }
}